package nuist.hanniko.stu.webbackend.interceptor;

import nuist.hanniko.stu.webbackend.dao.redis.LoginStateDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginStateHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginStateDAO loginStateDAO;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getParameterMap().get("token")[0];
            Object obj = loginStateDAO.getToken(token);
            if (obj == null) {
                response.sendError(200, "Login expired, plz login again.");
                return false;
            }
        } catch (Exception e) {
            response.sendError(200, "Missing token or unknown token.");
            return false;
        }
        return true;
    }
}
